package com.itheima.task;

import org.springframework.scheduling.annotation.Scheduled;

/**
 * 定时任务类
 */

import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@EnableScheduling
@Slf4j
public class ImageCleanTask {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private AliOssUtil aliOssUtil;

    private static final String UPLOAD_IMAGES_KEY = "upload:images";
    private static final String SETMEAL_IMAGES_KEY = "setmeal:images";

    /**
     * 每天凌晨2点执行清理任务
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void cleanImages() {
        log.info("开始执行定时清理垃圾图片任务");
        try {
            // 计算两个集合的差集，获取垃圾图片名称
            Set<String> garbageImages = redisTemplate.opsForSet().difference(UPLOAD_IMAGES_KEY, SETMEAL_IMAGES_KEY);

            if (garbageImages != null && !garbageImages.isEmpty()) {
                for (String imageName : garbageImages) {
                    try {
                        // 删除OSS中的图片
                        aliOssUtil.delete(imageName);
                        // 从Redis的上传图片集合中删除
                        redisTemplate.opsForSet().remove(UPLOAD_IMAGES_KEY, imageName);
                        log.info("成功删除垃圾图片：{}", imageName);
                    } catch (Exception e) {
                        log.error("删除垃圾图片失败：{}, 错误：{}", imageName, e.getMessage());
                    }
                }
            }
            log.info("垃圾图片清理任务执行完成，共清理{}张图片", garbageImages != null ? garbageImages.size() : 0);
        } catch (Exception e) {
            log.error("垃圾图片清理任务执行失败：{}", e.getMessage());
        }
    }
}
